﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Jemgine.MapEditor
{
    [Tools.SelectableTool]
    public class AssignBoneTool : BaseBoneTool
    {
        class BoneRefOpHook : Data.Terminal
        {
            Data.EntityElement Element;
            internal BoneRefOpHook(Data.EntityElement Element) { this.Element = Element; }

            public void SetTarget(object obj)
            {
                Element.BoneReference = obj as Data.Bone;
            }

            public object GetTarget()
            {
                return Element.BoneReference;
            }
        }

        public override System.Drawing.Image GetIcon() { return System.Drawing.Image.FromFile("ToolIcons/rotatebone.bmp"); }

        public override void MouseDown(MouseInputState InputState, EditorState EditorState)
        {
            if (EditorState.Selected.Type != Engine.Selection.Types.Vertex) return;
            var Skeleton = EditorState.GetMiddleObject(EditorState.Selected) as Data.Skeleton;
            if (Skeleton == null) return;
            var Bone = Skeleton.GetBone(EditorState.Selected.BottomIndex);

            var ObjectStack = EditorState.GetLocalElementStack(InputState.Position, EditorState.GetTopObject(
                EditorState.Selected) as Data.EntityRecord);

            if (ObjectStack.Count > 0)
                EditorState.PerformOperation(new Operations.TerminalTargetChanged(
                    new BoneRefOpHook(ObjectStack[0]), Bone));
        }

        public override void DrawExtra(Data.EditorDrawData Context, EditorState EditorState)
        {
            if (EditorState.Selected.Type != Engine.Selection.Types.Vertex) return;
            var Skeleton = EditorState.GetMiddleObject(EditorState.Selected) as Data.Skeleton;
            if (Skeleton == null) return;
            var Bone = Skeleton.GetBone(EditorState.Selected.BottomIndex);
            (EditorState.GetTopObject(EditorState.Selected) as Data.EntityRecord).DrawOutlinedElements(
                Context, (Element) => { return Element.BoneReference == Bone; });
        }
    }
}
